import { sendPasswordResetEmail } from '../../utils/email';
import { generateRandomCode } from '../../utils/crypto';
import { users, verificationCodes } from '../../database/schema';

export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  const { email } = body;

  const db = useDrizzle()

  // 检查用户是否存在
  const user = await db.select().from(users).where(eq(users.email, email)).limit(1);
  if (!user.length) {
    return { success: true }; // 防止邮箱枚举攻击
  }

  // 生成并保存重置码
  const code = generateRandomCode(6);
  const expiresAt = new Date(Date.now() + 15 * 60 * 1000); // 15分钟有效期

  await db.insert(verificationCodes).values({
    email,
    code,
    type: 'reset',
    expiresAt
  });

  // 发送重置邮件
  await sendPasswordResetEmail(email, code);

  return { success: true };
});